package com.aiti.lulian.pay.strategy.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.aiti.base.core.utils.stringUtil.StringUtil;
import com.aiti.lulian.entity.*;
import com.aiti.lulian.feign.CloudShowManagerSubService;
import com.aiti.lulian.mapper.CardVipRecordMapper;
import com.aiti.lulian.mapper.card.PayRemoteAddRoleFailMapper;
import com.aiti.lulian.pay.model.CardVipRecord;
import com.aiti.lulian.pay.model.PayInfo;
import com.aiti.lulian.pay.strategy.PayStrategy;
import com.aiti.lulian.service.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.*;
import java.util.concurrent.TimeUnit;

public abstract class AbstractPayStrategy implements PayStrategy {

    @Autowired
    protected RedisTemplate<String,String> redisTemplate;
    @Autowired
    private ILulianEnterpriseHistoryService historyService;
    @Autowired
    private ILuLianEnterpriseService enterpriseService;
    @Autowired
    private CloudShowManagerSubService managerSubService;

    protected String PAY_TOKEN_PRE = "ali:pay:token:%s";

    /***
     * redis比较和删除数据的 Lua脚本
     * 这个脚本在执行期间是原子性的操作
     */
    protected final String LUA_SCRIPT = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";

    @Autowired
    protected ICardVipRecordService service;

    @Autowired
    private CardVipRecordMapper vipRecordMapper;

    @Autowired
    private PayRemoteAddRoleFailMapper payRemoteAddRoleFailMapper;

    @Autowired
    private CardVipRecordMapper cardVipRecordMapper;

    @Autowired
    private ILuLianEnterpriseExtensionService luLianEnterpriseExtensionService;

    @Autowired
    private IEnterpriseDictDataService enterpriseDictDataService;

    @Autowired
    private ISysDataService sysDataService;

    /**
     * 将数据迁移到上线表中
     * @param enterpriseId
     */
    protected void dataMigration(String enterpriseId,String level,String userId, Integer payChannel, String orderId){

        LuLianEnterprise enterprise = enterpriseService.getOne(new QueryWrapper<LuLianEnterprise>().eq("base_id", enterpriseId));
        boolean isBasic;
        if(enterprise == null){
            LuLianEnterpriseHistory history = historyService.getById(enterpriseId);
            LuLianEnterprise luLianEnterprise = new LuLianEnterprise();
            BeanUtil.copyProperties(history,luLianEnterprise);
            luLianEnterprise.setMiniProgramVersion(StringUtil.equals(level,"基础版") ? 1 : 2);
            isBasic = StringUtil.equals(level, "基础版");
            Date currentDate = new Date();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(currentDate);
            calendar.add(Calendar.YEAR, 1);
            Date dateAfterOneYear = calendar.getTime();
            luLianEnterprise.setExpireTime(dateAfterOneYear);
            luLianEnterprise.setPayChannel(payChannel);
            enterpriseService.save(luLianEnterprise);
        }else{
            CardVipRecord cardVipRecord = cardVipRecordMapper.selectById(orderId);
            Date currentDate = new Date();
            Integer purchaseMiniProgramVersion =  StringUtil.equals(cardVipRecord.getVipLevel(),"基础版") ? 1 : 2;
            isBasic = StringUtil.equals(cardVipRecord.getVipLevel(), "基础版");
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(currentDate);
            calendar.add(Calendar.YEAR, 1);
            Date dateAfterOneYear = calendar.getTime();
            enterprise.setExpireTime(dateAfterOneYear);
            enterprise.setPayChannel(payChannel);
            enterprise.setMiniProgramVersion(purchaseMiniProgramVersion);
            enterpriseService.updateById(enterprise);
        }
        LuLianEnterpriseExtension extension = luLianEnterpriseExtensionService.getOne(new LambdaQueryWrapper<LuLianEnterpriseExtension>().eq(LuLianEnterpriseExtension::getEnterpriseId, enterpriseId));
        if (extension == null) {
            LuLianEnterpriseExtension build = LuLianEnterpriseExtension.builder().enterpriseId(enterpriseId).build();
            luLianEnterpriseExtensionService.save(build);
        }
        if (! isBasic) {
            List<EnterpriseDictData> enterpriseDictDataList = enterpriseDictDataService.list(new LambdaQueryWrapper<EnterpriseDictData>().eq(EnterpriseDictData::getEnterpriseId, enterpriseId));
            if (enterpriseDictDataList.size() == 0) {
                List<SysData> cardCustomerTypeList = sysDataService.list(new LambdaQueryWrapper<SysData>().eq(SysData::getDictTypeNo, "CARD_CUSTOMER_TYPE")
                        .orderByAsc(SysData::getBaseId));
                List<SysData> cardCustomerSourceList = sysDataService.list(new LambdaQueryWrapper<SysData>().eq(SysData::getDictTypeNo, "CARD_CUSTOMER_SOURCE")
                        .orderByAsc(SysData::getBaseId));
                List<SysData> cardCustomerFollowStatusList = sysDataService.list(new LambdaQueryWrapper<SysData>().eq(SysData::getDictTypeNo, "CARD_CUSTOMER_FOLLOW_STATUS")
                        .orderByAsc(SysData::getBaseId));
                int i = 0;
                int j = 0;
                int k = 0;
                List<EnterpriseDictData> dataList = new ArrayList<>();
                //默认的客户类型
                for (SysData cardCustomerType : cardCustomerTypeList) {
                    EnterpriseDictData cardCustomerTypeDictData = EnterpriseDictData.builder().dictTypeNo(cardCustomerType.getDictTypeNo()).dictTypeName("客户类型").baseName(cardCustomerType.getBaseName()).typeId(cardCustomerType.getTypeId())
                            .sort(i ++).isUpdated(StrUtil.equals(cardCustomerType.getBaseId(), "7ee01fe48a2647eb8b549acd28c45899") ? "0" : "1").module("8725839a-1488-4c30-9ef4-6d7369e28f00,8725839a-1488-4c30-9ef4-6d7369e28f01")
                            .enterpriseId(enterpriseId).creator("1").baseCreateTime(new Date()).build();
                    dataList.add(cardCustomerTypeDictData);
                }
                //默认的客户来源
                for (SysData cardCustomerSource : cardCustomerSourceList) {
                    EnterpriseDictData cardCustomerSourceDictData = EnterpriseDictData.builder().dictTypeNo(cardCustomerSource.getDictTypeNo()).dictTypeName("客户来源").baseName(cardCustomerSource.getBaseName()).typeId(cardCustomerSource.getTypeId())
                            .sort(j ++).isUpdated("1").module("8725839a-1488-4c30-9ef4-6d7369e28f00,8725839a-1488-4c30-9ef4-6d7369e28f01")
                            .enterpriseId(enterpriseId).creator("1").baseCreateTime(new Date()).build();
                    dataList.add(cardCustomerSourceDictData);
                }
                //默认的跟进状态
                for (SysData cardCustomerFollowStatus : cardCustomerFollowStatusList) {
                    EnterpriseDictData cardCustomerFollowStatusDictData = EnterpriseDictData.builder().dictTypeNo(cardCustomerFollowStatus.getDictTypeNo()).dictTypeName("跟进状态").baseName(cardCustomerFollowStatus.getBaseName()).typeId(cardCustomerFollowStatus.getTypeId())
                            .sort(k ++).isUpdated((StrUtil.equals(cardCustomerFollowStatus.getBaseId(), "c661b397f83a4fd590f3c79ac4040dad1") || StrUtil.equals(cardCustomerFollowStatus.getBaseId(), "c661b397f83a4fd590f3c79ac4040dad4")) ? "0" : "1").module("8725839a-1488-4c30-9ef4-6d7369e28f00,8725839a-1488-4c30-9ef4-6d7369e28f01,8725839a-1488-4c30-9ef4-6d7369e28f03,8725839a-1488-4c30-9ef4-6d7369e28f04")
                            .enterpriseId(enterpriseId).creator("1").baseCreateTime(new Date()).build();
                    dataList.add(cardCustomerFollowStatusDictData);
                }
                enterpriseDictDataService.saveBatch(dataList);
            }
        }

        Map<String,String> params = new HashMap<>(16);
        params.put("userId",userId);
        params.put("roleId","043ea2e3e02c4aa591df1f83e65069bc");

        int countUserRoleCount = vipRecordMapper.selectUserRole(userId,"043ea2e3e02c4aa591df1f83e65069bc");
        if(countUserRoleCount <= 0){
            vipRecordMapper.insertUserRole(IdUtil.simpleUUID(),userId,"043ea2e3e02c4aa591df1f83e65069bc");
        }
//        Message message = managerSubService.addUserRole(params);
//        if(message.getCode().equals(MessageCodeConstant.MSG_FAIL_CODE)){
//            //如果远程调用失败，则
//            PayRemoteAddRoleFail build = PayRemoteAddRoleFail.builder()
//                    .baseId(IdUtil.simpleUUID())
//                    .userId(userId)
//                    .roleId("043ea2e3e02c4aa591df1f83e65069bc")
//                    .build();
//            payRemoteAddRoleFailMapper.insert(build);
//        }
    }

    /**
     * 获取token
     * @param userId 用户Id
     * @return
     */
    @Override
    public String genToken(String userId){
        String token = IdUtil.simpleUUID();
        redisTemplate.opsForValue().set(String.format(PAY_TOKEN_PRE,userId), token,30, TimeUnit.MINUTES);
        return token;
    }

    /**
     * 创建订单信息
     * @param payInfo 支付信息
     * @return 订单结果
     */
    public CardVipRecord createOrder(PayInfo payInfo) {
//        LambdaQueryWrapper<CardVipRecord> lqw = new LambdaQueryWrapper<>();
//        lqw.eq(CardVipRecord::getVipId, payInfo.getVipId());
//        lqw.eq(CardVipRecord::getPayType,payInfo.getPayType());
//        lqw.eq(CardVipRecord::getEnterpriseId,payInfo.getEnterpriseId());
//        lqw.eq(CardVipRecord::getUserId,payInfo.getUserId());
//        lqw.eq(CardVipRecord::getPayAmount,payInfo.getPayAmount());
//        lqw.eq(CardVipRecord::getOrderStatus,"0");
//        lqw.orderByDesc(CardVipRecord::getBaseCreateTime);
//
//        List<CardVipRecord> list = service.list(lqw);
//        if(list != null && !list.isEmpty()){
//            return list.get(0);
//        }else{
//            CardVipRecord vipRecord = CardVipRecord.builder()
//                    .baseId(IdUtil.simpleUUID())
//                    .baseCreateTime(DateUtil.date())
//                    .enterpriseId(payInfo.getEnterpriseId())
//                    .userId(payInfo.getUserId())
//                    .payType(payInfo.getPayType())
//                    .vipId(payInfo.getVipId())
//                    .vipLevel(payInfo.getVipName())
//                    .payAmount(payInfo.getPayAmount())
//                    .build();
//            service.save(vipRecord);
//            return vipRecord;
//        }
        CardVipRecord vipRecord = CardVipRecord.builder()
                .baseId(IdUtil.simpleUUID())
                .baseCreateTime(DateUtil.date())
                .enterpriseId(payInfo.getEnterpriseId())
                .userId(payInfo.getUserId())
                .payType(payInfo.getPayType())
                .vipId(payInfo.getVipId())
                .vipLevel(payInfo.getVipName())
                .payAmount(payInfo.getPayAmount())
                .build();
        service.save(vipRecord);
        return vipRecord;
    }

    public boolean updateOrder(CardVipRecord record) {
        service.updateById(record);
        return true;
    }

    public String convert(long fen) {
        if (fen < 0) {
            throw new RuntimeException("金额转换失败");
        }

        long yuan = fen / 100;
        long remainingFen = fen % 100;

        return String.format("%d.%02d", yuan, remainingFen);
    }

}
